<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="main-box" :loading="!getSystemDataDone">
    <CommonDateSearch v-if="getSystemDataDone" ref="searchRef" @search="handleSearch" :extraSearch="currentTab == 'detail'? extraSearch : []">
    </CommonDateSearch>
    <div class="content-box">
      <div class="tab">
        <a-radio-group v-model:value="currentTab" button-style="solid" @change="changeRadio">
          <a-radio-button value="detail">冷热源流量明细</a-radio-button>
          <a-radio-button value="distribution">冷热源流量分布图</a-radio-button>
        </a-radio-group>
        <a-button style="float: right;margin-right: 18px;" type="primary" @click="handleExport"
          :loading="exportLoading">导出</a-button>

      </div>
      <template v-if="currentTab === 'detail'">
        <div class="chart-box">
          <Line :loading="loadingRef" :chartData="chartData" title="数据" />
        </div>
        <a-card class="common-card flex table-box" title="数据报表">
          <BasicTable @register="registerTable" :loading="loadingRef">
          </BasicTable>
        </a-card>
      </template>
      <template v-else>
        <Detail :searchInfo="searchInfo" ref="childComponent" />
      </template>
    </div>
  </PageWrapper>
</template>
<script setup lang="ts">
import { PageWrapper } from '@/components/Page'
import Detail from './Detail.vue'
import CommonDateSearch from '@/components/CommonDateSearch/index.vue'
import { ref, onMounted, reactive, nextTick } from 'vue'
import { BasicTable, useTable, BasicColumn } from '@/components/Table'
import { getChildDataLengRe } from '@/api/dataReport/deviceParamReport.ts'
import Line from '@/components/Charts/Line/index.vue'
import { getClassifyTreeByPatent } from '@/api/collection/classify'
import { chartchildDataLengReExport } from '@/api/common/chart.ts'
import {
  downloadByData,
} from '@/utils/file/download';

defineOptions({ name: 'ColdAndHotSource' })
const childComponent = ref()
const currentTab = ref('detail')
const searchInfo = reactive({
  classifyId: '', // 新增：将classifyId提升到searchInfo中
})
let searchRef = ref()
const getSystemDataDone = ref(false)
const systemOptions = ref([])
const idMatchParentName = ref({})
const loadingRef = ref(true)
const chartData = ref({
  xaxisList: [],
  yaxisList: [],
})
const exportLoading = ref(false)
const extraSearch = ref([
  {
    field: 'system',
    label: '系统选择',
    component: 'Select',
    required: true,
    colProps: { span: 4 },
    componentProps: ({ formModel, formActionType }) => {
      return {
        options: systemOptions,
        labelInValue: true,
        fieldNames: {
          label: 'classifyName',
          value: 'classifyId',
        },
        onChange: async (systemData) => {
          formModel.point = undefined
          idMatchParentName.value = {}
          const { updateSchema } = formActionType
          const pointOptions = systemData.option.children || []
          updateSchema({
            field: 'point',
            componentProps: {
              options: pointOptions,
              labelInValue: true,
              fieldNames: {
                label: 'classifyName',
                value: 'classifyId',
              }
            }
          })
        }
      }
    },
  },
  {
    field: 'point',
    label: '点位选择',
    required: true,
    component: 'Select',
    colProps: { span: 4 },
    loading: true,
  },
])
const [registerTable, { setColumns, setTableData }] = useTable({
  rowKey: 'id',
  columns: [],
  pagination: false,
  formConfig: {
    labelWidth: 120,
  },
  bordered: true,
  striped: false,
})
const handleExport = async () => {
  searchInfo.dictCode = "LengReExport"
  searchInfo.itemName = "冷热源系统"
  exportLoading.value = true
  const { data, headers } = await chartchildDataLengReExport(searchInfo)
  let contentDisposition = decodeURIComponent(headers["content-disposition"]);
  const filenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)|filename="(.+)"|filename=(.+)/)
  const fileName = filenameMatch[1] || filenameMatch[2] || filenameMatch[3]
  downloadByData(data, fileName);
  exportLoading.value = false
  message.success("导出成功");
}
const changeRadio = (params) => {
  if (params.target.value == 'distribution') {
    // searchRef.value.handleSearch()
  } else {
    searchRef.value.handleSearch()
  }
}
onMounted(async () => {
  await getSystemData()
})

const getSystemData = async () => {
  const res = await getClassifyTreeByPatent({ parentClassifyId: '1834054101655097344', type: 1 })
  getSystemDataDone.value = true
  systemOptions.value = res[0].children || []
  await nextTick()
  const systemData = res[0].children[0]
  const pointData = systemData.children[0]
  await searchRef.value.setFieldsValue({
    system: {
      label: systemData.classifyName,
      value: systemData.classifyId,
      option: systemData
    },
    point: {
      label: pointData.classifyName,
      value: pointData.classifyId,
      option: pointData
    }
  })
  searchRef.value.handleSearch()
}
const handleSearch = (params) => {
  const { point, system, ...others } = params
  Object.assign(searchInfo, others)
  getMatchIds({ point })
  getData()
  childComponent.value?.handleSearch(params)
}

const getMatchIds = (params) => {
  if (params.point) {
    const pointData = params.point.option
    searchInfo.classifyId = pointData.classifyId // 直接将classifyId存入searchInfo
    idMatchParentName.value = { [pointData.classifyName]: pointData.classifyName }
  }
}

const getData = async () => {
  loadingRef.value = true
  // 移除deviceList，直接传递searchInfo（包含classifyId）
  getChildDataLengRe({ ...searchInfo }).then(res => {
    chartData.value = res
    formatTableData()
  }).catch(() => {
    chartData.value = { xaxisList: [], yaxisList: [] }
    formatTableData()
  }).finally(() => {
    loadingRef.value = false
  })
}

const formatTableData = () => {
  formatHeader()
  formatTbody()
}

const formatHeader = () => {
  const headerList: BasicColumn[] = chartData.value.xaxisList.map((item) => ({
    title: item,
    dataIndex: item,
    width: 80,
    customRender: ({ text }) => {
      return text || '--'
    },
  }))
  headerList.unshift({
    title: '数据名称',
    dataIndex: 'name',
    width: 220,
    fixed: 'left',
  })

  setColumns(headerList)
}

const formatTbody = () => {
  const { xaxisList, yaxisList } = chartData.value
  const data = yaxisList.map((item: any) => {
    const { data, name, stack, ...others } = item
    const labelName = idMatchParentName.value[name] || ''
    const record = { ...others, name: `${name}` }
    data.forEach((item, index) => {
      record[xaxisList[index]] = item
    })
    return record
  })
  setTableData(data)
}
</script>

<style scoped lang="scss">
.content-box {
  display: flex;
  flex: 1;
  flex-direction: column;
  background: #fff;
  overflow: hidden;
  .chart-box {
    padding: 8px 8px 4px;
  }

  .chart-box,
  .table-box {
    flex: 1;
    flex-shrink: 0;
    overflow: hidden;
  }

  :deep(.ant-table-wrapper) {
    padding: 0;
  }
}
</style>    
